package com.yiwei.hdb.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.yiwei.hdb.R;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.api.bean.DealPhotoV3Bean;
import com.yiwei.hdb.api.bean.ModifyFaceBean;
import com.yiwei.hdb.api.bean.SubmitApplyBean;
import com.yiwei.hdb.api.bean.UploadImageBean;
import com.yiwei.hdb.constant.FaceBitmap;
import com.yiwei.hdb.constant.UserGlobal;
import com.yiwei.hdb.event.IdcardFaceEvent;
import com.yiwei.hdb.util.ImageUtil;
import com.yiwei.hdb.util.Network;
import com.yiwei.hdb.util.PreferenceUtils;
import com.yiwei.hdb.util.RxLifeUtil;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.Dialog;
import com.yiwei.hdb.view.LoadingSecDialog;
import com.yiwei.hdb.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3FaceIdentityTwoActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    private Unbinder unbinder;
    private LoadingSecDialog loadingSecDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_identity_two_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("人脸认证");
        EventBus.getDefault().register(this);
        loadingSecDialog = new LoadingSecDialog(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (FaceBitmap.bitmap != null && !FaceBitmap.bitmap.isRecycled()) {
            FaceBitmap.bitmap.recycle();
            FaceBitmap.bitmap = null;
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        unbinder = null;
    }

    /**
     * 获取相机权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermission() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                Intent localIntent = new Intent(V3FaceIdentityTwoActivity.this, FaceActivity.class);
                startActivityForResult(localIntent, 100);
            }

            @Override
            public void superReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IdcardFaceEvent event) {
        if (FaceBitmap.bitmap != null) {
            uploadImg(ImageUtil.Bitmap2StrByBase64(FaceBitmap.bitmap, 100));  //上传颜值
        }
    }


    public void getSubmitApply(String lat, String lng) {

        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        loadingSecDialog.setTip("此过程需要2～5分钟，期间请勿退出软件").show();
        SubmitApplyBean bean = new SubmitApplyBean();
        bean.deal_id = UserGlobal.getDealId();
        bean.lat = lat;
        bean.lng = lng;
        bean.use_type = UserGlobal.getUseType();
//        bean.bankcard_id = UserGlobal.getPayBankcard();
        Api.api_service.getSubmitApplyInfo(bean).compose(RxLifeUtil.NocheckOnDestroy(this)).
                doFinally(() -> {
                    try {
                        loadingSecDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(item -> {
                    if (item.getStatus() == 1) {
                        Dialog.showSubmitSuccessV3(this, new Dialog.DialogClickListener() {
                            @Override
                            public void confirm() {
                                Util.startActivity(V3FaceIdentityTwoActivity.this, MainActivityNew.class);
                                finish();
                            }
                        }).show();

                    } else {
                        ToastUtil.makeText(this, item.getMsg()).show();
                    }
//                    if ((item.getStatus() == 0 && item.getMsg().equals("未通过")) || item.getStatus() != 0) {

//                    } else {
//                        ToastUtil.makeText(this, item.getMsg()).show();
//                    }
                });
    }

    public void updateFace(String url) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        DealPhotoV3Bean bean = new DealPhotoV3Bean();
        bean.deal_id = UserGlobal.getDealId();
        bean.imgurl = url;
        Api.api_service.getDealPhotoV3(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    loadingDialog.dismiss();
                    ToastUtil.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT);
                    txtRight.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            getSubmitApply(PreferenceUtils.getString(V3FaceIdentityTwoActivity.this, "lat", ""), PreferenceUtils.getString(V3FaceIdentityTwoActivity.this, "lng", ""));

                        }
                    }, 150);

                });
    }

    public void uploadImg(String img) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        UploadImageBean bean = new UploadImageBean();
        bean.img = img;
        Api.api_service.uploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    loadingDialog.dismiss();
                    updateFace(result.getUrl());
                });
    }


    @OnClick({R.id.btn_back, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit:
                checkPermission();
                break;
        }
    }
}
